// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"flag"
	"net/http"
	"text/template"
	"fmt"
	"log"
	"webmonitor/websocket"
	"os"
	"bytes"
	"path/filepath"
)


var (

	addr = flag.String("addr", ":8080", "http service address")


	homeTemplate =template.Must(template.ParseFiles(getTemplatesPath()))
)

func getTemplatesPath()string{
	root_path,_ := os.Getwd()
	path := bytes.Buffer{}
	path.WriteString(root_path)
	local_path:=filepath.FromSlash("/../templates/home.html")
	path.WriteString(local_path)
	return path.String()
}

func serveHome(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.Error(w, "Not found", 404)
		return
	}
	if r.Method != "GET" {
		http.Error(w, "Method not allowed", 405)
		return
	}
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	homeTemplate.Execute(w, r.Host)

}


func main() {

	flag.Parse()
	hub := websocket.NewHub()
	go hub.Run()
	fs := http.FileServer(http.Dir("../static/"))
	http.Handle("/static/", http.StripPrefix("/static/", fs))
	http.HandleFunc("/", serveHome)
	http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		websocket.ServeWs(hub, w, r)
	})
	fmt.Printf(" server on %d", 8080)
	err := http.ListenAndServe(*addr, nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
